<?php

namespace app\company\controller\report\subset;

use app\BaseController;
use app\model\DepartmentAdminModel;
use app\model\InterpretationRecordModel;
use app\model\ProxyEvaluationResultModel;
use app\model\RatingScaleModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserResultModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class ExplainReport extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 申请解读记录
     * @return bool|string
     */
    public function Index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|单位ID' => 'require'
            ]);
            $where = [];
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
            $InterpretationRecordModel = new InterpretationRecordModel();
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['explain_uid'])) {
                $where[] = ['explain_uid', '=', $param['explain_uid']];
            }
            if (!empty($param['source'])) {
                $where[] = ['source', '=', $param['source']];
            }
            $ResultWhere = [];
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $ResultWhere[] = ['is_warning', '=', $param['is_warning']];
            }
            if (!empty($param['admin'])) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $UserModel = new UserModel();
                $department_id = $DepartmentAdminModel->where('uid', '=', $param['admin'])->column('department_id');
                $uid = [];
                if (count($department_id) > 0) {
                    $uid = $UserModel->where('department_id', 'in', $department_id)->column('uid');
                }
                if (count($uid) > 0) {
                    $ResultWhere[] = ['uid', 'in', $uid];
                } else {
                    $ResultWhere[] = ['id', '=', -1];
                }
            }
            $ids = [];
            if (!empty($param['name'])) {
                $TaskModel = new TaskModel();
                $task_id = $TaskModel->where([
                    ['unit_id', 'in', $this->userData['subset_unit']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_id = $RatingScaleModel->where([
                    ['unit_id', 'in', $this->userData['subset_unit']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['unit_id', 'in', $this->userData['subset_unit']],
                    ['name', 'like', '%' . $param['name'] . '%']
                ])->column('id');
                $task_where = [];
                $self_where = [];
                $proxy_where = [];
                if (count($task_id)) {
                    $task_where[] = ['task_id', 'in', $task_id];
                } else {
                    $task_where[] = ['task_id', '=', -1];
                }
                if (count($rating_scale_id)) {
                    $task_where[] = ['rating_scale_id', 'in', $rating_scale_id];
                    $self_where[] = ['rating_scale_id', 'in', $rating_scale_id];
                    $proxy_where[] = ['rating_scale_id', 'in', $rating_scale_id];
                } else {
                    $task_where[] = ['rating_scale_id', '=', -1];
                    $self_where[] = ['rating_scale_id', '=', -1];
                    $proxy_where[] = ['rating_scale_id', '=', -1];
                }
                if (count($uid)) {
                    $task_where[] = ['uid', 'in', $uid];
                    $self_where[] = ['uid', 'in', $uid];
                    $proxy_where[] = ['uid', 'in', $uid];
                } else {
                    $task_where[] = ['uid', '=', -1];
                    $self_where[] = ['uid', '=', -1];
                    $proxy_where[] = ['uid', '=', -1];
                }
                //任务
                $result_id = $TaskUserResultModel->where($ResultWhere)->whereOr($task_where)->column('id');
                if (count($result_id)) {
                    $id = $InterpretationRecordModel->where([
                        ['source', '=', 1],
                        ['result_id', 'in', $result_id]
                    ])->column('id');
                    $ids = array_merge($ids, $id);
                }
                //自我
                $result_id = $SelfEvaluationResultModel->where($ResultWhere)->whereOr($self_where)->column('id');
                if (count($result_id)) {
                    $id = $InterpretationRecordModel->where([
                        ['source', '=', 2],
                        ['result_id', 'in', $result_id]
                    ])->column('id');
                    $ids = array_merge($ids, $id);
                }
                //他人
                $result_id = $ProxyEvaluationResultModel->where($ResultWhere)->whereOr($proxy_where)->column('id');
            } else {
                //任务
                $result_id = $TaskUserResultModel->where($ResultWhere)->column('id');
                if (count($result_id)) {
                    $id = $InterpretationRecordModel->where([
                        ['source', '=', 1],
                        ['result_id', 'in', $result_id]
                    ])->column('id');
                    $ids = array_merge($ids, $id);
                }
                //自我
                $result_id = $SelfEvaluationResultModel->where($ResultWhere)->column('id');
                if (count($result_id)) {
                    $id = $InterpretationRecordModel->where([
                        ['source', '=', 2],
                        ['result_id', 'in', $result_id]
                    ])->column('id');
                    $ids = array_merge($ids, $id);
                }
                //他人
                $result_id = $ProxyEvaluationResultModel->where($ResultWhere)->column('id');
            }
            if (count($result_id)) {
                $id = $InterpretationRecordModel->where([
                    ['source', '=', 3],
                    ['result_id', 'in', $result_id]
                ])->column('id');
                $ids = array_merge($ids, $id);
            }
            if (count($ids)) {
                $ids = array_unique($ids);
                $where[] = ['id', 'in', $ids];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $param['unit_id']];
            $query = $InterpretationRecordModel->where($where);
            $data = $query->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                switch ($item['source']) {
                    case 1:
                        $item['source_name'] = '任务测评';
                        $info = $TaskUserResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'task',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 2:
                        $item['source_name'] = '自我测评';
                        $info = $SelfEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    case 3:
                        $item['source_name'] = '他人代测';
                        $info = $ProxyEvaluationResultModel->with([
                            'user' => function ($query) {
                                $query->with([
                                    'department' => function ($query) {
                                        $query->with([
                                            'departmentAdmins' => function ($query) {
                                                $query->with(['userName']);
                                            }
                                        ]);
                                    },
                                    'unitName'
                                ]);
                            },
                            'RatingScaleFactorWarningModel',
                            'RatingScale' => function ($query) {
                                $query->with(['ratingScaleTypeName']);
                            }
                        ])->find($item['result_id']);
                        break;
                    default:
                        break;
                }
                if (!isset($info)) {
                    continue;
                }
                $item = [
                    'id' => $item['id'],
                    'rating_scale_name' => $info['rating_scale_name'],
                    'rating_scale_cover' => $info['rating_scale_cover'],
                    'interpretation_fee' => $info['interpretation_fee'],
                    'is_explain' => $info['is_explain'],
                    'source' => $item['source_name'],
                    'task_name' => $info['task_name'] ?? '--',
                    'user_name' => $info['user_name'],
                    'sex' => $info['sex'],
                    'age' => $info['age'],
                    'unit_name' => $info['unit_name'],
                    'department_name' => $info['department_name'],
                    'department_admins' => $info['departmentAdmins'] ?? [],
                    'result_read_auth' => $info['result_read_auth'],
                    'time' => $item['time'],
                    'student_status' => $info['student_status'],
                    'username' => $info['username'],
                    'user_number' => $info['uid'],
                    'rating_scale_type_name' => $info['rating_scale_type_name'],
                    'total_score' => $info['total_score'],
                    'is_warning' => $info['is_warning'],
                    'warning_name' => $info['warning_name'],
                    'answer_role' => $info['answer_role'],
                ];
            }
            $data['ids'] = $query->column('id');
            $UnitModel = new UnitModel();
            $data['unit_name'] = $UnitModel->where('id','=',$param['unit_id'])->cache(true,60)->value('name');
            return success(['data' => $data, 'total' => $query->where('is_explain','in',[1,2])->count()]);
        } catch (\Exception $e) {
            return error($e->getMessage() . $e->getLine());
        }
    }
}